function P = bp(A, W, Y, lambda)
% 后向传播求偏导
% input:
%     A - matrix cell array
%     Y - matrix
%     J - scalar
% output:
%     P - matrix cell array

% 求每一层的偏导
    m = size(Y, 1);
    l = length(A);
    Delta{l} = 1 / m * (A{l} - Y) .* (A{l} .* (1 - A{l}));
    Delta{l - 1} = Delta{l} * W{l - 1} .* (A{l - 1} .* (1 - A{l - 1}));
    for k = l - 2: -1: 2
        % 偏置单元与前一层的偏导无关
        D = Delta{k + 1}(:, 2: end); 
        Delta{k} = D * W{k} .* (A{k} .* (1 - A{k}));
    end

    % 求权重的偏导
    l = length(W);
    for k = 1: l - 1
        D = Delta{k + 1}(:, 2: end);
        P{k} = D' * A{k};
        % 加入正则化项的偏导
        P{k} = P{k} + lambda / m * W{k};
    end
    P{l} = (Delta{l + 1})' * A{l} + lambda / m * W{l};
end